from sklearn import svm
import pandas as pd
import sys
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import r2_score
def load_train_data(file):
    data = pd.read_csv(file)
    location = data[['x', 'y', 'z']].values
    grade = data['grade'].values
    return location,grade

def load_test_data(file):
    data = pd.read_csv(file)
    location = data[['x', 'y', 'z']].values
    return location
def Createmodel(train_x,train_y,C1):
    model =svm.SVR(kernel='rbf',C=C1)
    model.fit(train_x, train_y)
    return model

def predict(model,test_x):
    my_model=model
    test_y=model.predict(test_x)
    return test_y

def run(argv):
    file=argv[1]
    file1=argv[2]
    C=argv[3]
    train_x,train_y=load_train_data(file)
    test_x=load_test_data(file1)
    mymodel=Createmodel(train_x,train_y,float(C))
    #mymodel = mymodel.fit(train_x, train_y)
    test_y=predict(mymodel,test_x)
#精度设置，预估品位值保留小数点后四位
    for i in range(len(test_y)):
        test_y[i]=round(test_y[i], 4)
        if test_y[i]<0:
            test_y[i]=0;
    test = pd.read_csv(file1)
    test["grade"] = test_y
    test.to_csv("./pyscript/data/myresult.csv", index=None)
    print('模型得分:{:.2f}'.format(mymodel.score(test_x, test_y)))
    y_pre = predict(mymodel, train_x)
    print('模型均方误差MSE:{:.4f}'.format(mean_squared_error(train_y, y_pre)))
    print('模型平均绝对误差MAE:{:.4f}'.format(mean_absolute_error(train_y, y_pre)))
    print('模型决定系数R:{:.4f}'.format(r2_score(train_y, y_pre)))
    with open("./pyscript/data/evaluate.txt", "w") as f:
        f.write('SVM算法')
        f.write('，惩罚系数:{:.2f}\n'.format(float(C)))
        #f.write('模型得分:{:.2f}\n'.format(mymodel.score(test_x, test_y)))
        f.write('模型均方误差MSE:{:.4f}\n'.format(mean_squared_error(train_y, y_pre)))
        f.write('模型平均绝对误差MAE:{:.4f}\n'.format(mean_absolute_error(train_y, y_pre)))

#argv=['da.csv','te.csv']
#run(argv)
#输入参数：训练文件，测试文件,惩罚因子
#run(sys.argv)

try:
    run(sys.argv)
except:
    print("svm异常")

